﻿using dz.util.core;
using System;
using System.Security.Cryptography;
using System.Text;

namespace Dz.WorkerService
{
    internal class JkyUtils
    {
        private const string VERSION = "v1.0";
        //正式
        private const string APPKEY = "70033959";
        private const string APPSECRET = "ea4c56d185ba40d8abfcba93301b66e9";
        private const string URL = "https://open.jackyun.com/open/openapi/do";
        //测试
        //private const string APPKEY = "10526885";
        //private const string APPSECRET = "81c0332dc7a94e168504a3c866f79043";        
        //private const string URL = "https://open.jackyun.com/open/openapi/do";
        /// <summary>
        /// 计算给定字符串的 MD5 值（32 位小写十六进制）
        /// </summary>
        /// <param name="input">待加密字符串</param>
        /// <param name="encoding">字符编码，默认 UTF-8</param>
        /// <returns>MD5 哈希值（小写）</returns>
        public static string GetMd5(string input, Encoding? encoding = null)
        {
            if (input == null) throw new ArgumentNullException(nameof(input));

            if (encoding == null)
                encoding = Encoding.UTF8;

            using (MD5 md5 = MD5.Create())
            {
                byte[] hashBytes = md5.ComputeHash(encoding.GetBytes(input));
                var sb = new StringBuilder(32);
                foreach (byte b in hashBytes)
                    sb.Append(b.ToString("x2"));  // 小写十六进制
                return sb.ToString();
            }
        }

        public static string GetParm(string method, string bizcontent)
        {
            var dic = new SortedDictionary<string, string>();
            dic.Add("method", method);
            dic.Add("appkey", APPKEY);
            dic.Add("version", VERSION);
            dic.Add("contenttype", "json");
            dic.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));            
            dic.Add("bizcontent", bizcontent);

            // 构建待签名的字符串。
            StringBuilder sbSignData = new StringBuilder(APPSECRET);
            foreach (var entry in dic)
            {
                sbSignData.Append(entry.Key + entry.Value);
            }
            sbSignData.Append(APPSECRET);

            string signStr = sbSignData.ToString().ToLower();


            dic.Add("sign", GetMd5(signStr));

            StringBuilder sbPostData = new StringBuilder();
            foreach (var entry in dic)
            {
                sbPostData.Append("&").Append(entry.Key).Append("=").Append(entry.Value);
            }

            string postDataStr = sbPostData.ToString().Substring(1);

            return postDataStr;
        }

        public static async Task<WebResult> PostByQM(string method, string bizcontent)
        {
            HttpUtil util = new HttpUtil();
            QmParm parm = new QmParm();
            parm.bizcontent= bizcontent;

            string url = "https://work.jertop.com/api/flows/webhook/anyTenant/flow/1955544833261461504";
            WebResult result = await util.Post(url, JsonUtil.Serialize(parm));

            return result;
        }

        public static async Task<WebResult> Post(string method, string bizcontent)
        {
            HttpUtil util = new HttpUtil();

            WebResult result = await util.Post(URL,GetParm(method,bizcontent), "application/x-www-form-urlencoded");

            return result;
            
        }
        /* 带金额的接口
        https://work.jertop.com/api/flows/webhook/anyTenant/flow/1955544833261461504
        {
    "method": "jackyun.tradenotsensitiveinfos.list.get",
    "jdy_key": "b37oOn1zcohHnHDjKsp0",
    "bizcontent": {
        "hasTotal": null,
        "startBillDate": null,
        "isTableSwitch": null,
        "pageSize": 10,
        "endBillDate": null,
        "endSettleAuditTime": null,
        "scrollId": null,
        "endCreated": null,
        "settleGmtCreateStartTime": null,
        "endAuditTime": null,
        "shopIds": null,
        "startAuditTime": null,
        "warehouseIds": null,
        "tradeType": null,
        "endSigningTime": null,
        "tradeNo": "JY2025091717905",
        "startSettleTime": null,
        "tradeTypeList": null,
        "mainPostId": null,
        "isDelete": null,
        "startModified": null,
        "startSigningTime": null,
        "startSettleAuditTime": null,
        "endModified": null,
        "startCreated": null,
        "tradeFrom": null,
        "mainPostIdList": null,
        "pageIndex": 0,
        "sourceTradeNos": null,
        "tradeStatus": null,
        "endSettleTime": null,
        "endCompleteTime": null,
        "startCompleteTime": null,       
        "fields": "tradeNo,chargeCurrency,goodsDetail.goodsNo,goodsDetail.sellCount,goodsDetail.unit,goodsDetail.platCode,goodsDetail.platGoodsId,customerCode,warehouseCode,warehouseName,tradeId,shopcode,scrollId,goodsDetail.isFit,flagNames,goodsDetail.sellTotal,goodsDetail.taxFee,tradeOrderAssemblyGoodsDtoList.sellTotal,tradeOrderAssemblyGoodsDtoList.taxFee,radeOrderAssemblyGoodsDtoList.goodsNo,tradeOrderAssemblyGoodsDtoList.taxRate,tradeOrderAssemblyGoodsDtoList.sellCount,tradeOrderAssemblyGoodsDtoList.sellTotal"
    }
}

        */
    }
}
